<template>
  <div>
    <el-card shadow="hover" :body-style="{ padding: '20px' }">
      <!-- 添加按钮 -->
      <el-button
        type="primary"
        :icon="Plus"
        @click="addButtonHandler"
        v-hidden="'btn.Trademark.add'"
        >添加</el-button
      >
      <!-- 品牌列表 -->
      <el-table
        v-loading="loading"
        :data="trademarkList.records"
        border
        style="margin: 20px 0"
      >
        <el-table-column
          type="index"
          label="序号"
          align="center"
          width="80px"
        />
        <el-table-column prop="tmName" label="品牌名称" />
        <el-table-column label="品牌LOGO">
          <template #="{ row, $index }">
            <a href="http://jd.com" :title="row.tmName"
              ><img :src="row.logoUrl" style="width: 100px; height: 60px"
            /></a>
          </template>
        </el-table-column>
        <el-table-column prop="address" label="操作">
          <template #="{ row, $index }">
            <el-button
              type="warning"
              :icon="Edit"
              size="small"
              @click="updateTrademark(row)"
              v-hidden="'btn.Trademark.update'"
            ></el-button>
            <el-popconfirm
              :title="`确定要删除${row.tmName}吗？`"
              @confirm="deleteTrademark(row)"
            >
              <template #reference>
                <el-button
                  type="danger"
                  :icon="Delete"
                  v-hidden="'btn.Trademark.remove'"
                  size="small"
                ></el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页器 -->
      <el-pagination
        v-model:currentPage="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[3, 5, 7]"
        background
        layout="prev, pager, next, jumper, ->, sizes, total"
        :total="trademarkList.total"
        @size-change="handleSizeChange"
        @current-change="getTrademarkList"
      />
      <!-- 添加品牌 -->
      <el-dialog
        v-model="dialogFormVisible"
        :title="addTrademarkParams.id ? '修改品牌' : '添加品牌'"
        width="50%"
        draggable
      >
        <el-form
          label-width="90px"
          style="width: 80%"
          :model="addTrademarkParams"
          :rules="rules"
          ref="formRef"
        >
          <el-form-item label="品牌名称" prop="tmName">
            <el-input autocomplete="off" v-model="addTrademarkParams.tmName" />
          </el-form-item>
          <el-form-item label="品牌LOGO" prop="logoUrl">
            <el-upload
              class="avatar-uploader"
              action="/api/admin/product/fileUpload"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
            >
              <img
                v-if="addTrademarkParams.logoUrl"
                :src="addTrademarkParams.logoUrl"
                class="avatar"
              />
              <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            </el-upload>
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取消</el-button>
            <el-button type="primary" @click="addTrademark">确定</el-button>
          </span>
        </template>
      </el-dialog>
    </el-card>
  </div>
</template>

<script lang="ts">
export default {
  name: "Trademark",
};
</script>

<script lang="ts" setup>
import type { UploadProps, FormRules, FormInstance } from "element-plus";
import { ElMessage } from "element-plus";
import { Plus, Edit, Delete } from "@element-plus/icons-vue"; // 引入icon图标
import { ref, onMounted, reactive, nextTick } from "vue";

import {
  reqTrademarkList,
  reqAddOrUpdateTrademark,
  reqDeleteTrademark,
} from "@/api/product/Trademark"; // 请求函数
import type { ITrademarkList, ITrademark } from "@/api/product/Trademark/model"; // 参数接口

const currentPage = ref<number>(1); // 当前页数
const pageSize = ref<number>(3); // 每页展示条数
const loading = ref<boolean>(false); // 加载效果
const dialogFormVisible = ref<boolean>(false); // 添加品牌的表单的状态
const formRef = ref<FormInstance>(); // form表单对象

// 分页列表数据
const trademarkList = reactive<ITrademarkList>({
  records: [],
  total: 0,
});

// 添加或修改品牌的参数
const addTrademarkParams = reactive<ITrademark>({
  tmName: "",
  logoUrl: "",
});

// 获取分页列表数据
const getTrademarkList = async (page: number = 1) => {
  loading.value = true;
  currentPage.value = page;

  const result = await reqTrademarkList(currentPage.value, pageSize.value);
  loading.value = false;

  trademarkList.records = result.records;
  trademarkList.total = result.total;
};

// 改变数据展示条数 并重新获取分页列表数据
const handleSizeChange = (limit: number) => {
  pageSize.value = limit;

  getTrademarkList();
};

// 数据(图片)上传成功时的钩子
const handleAvatarSuccess: UploadProps["onSuccess"] = (
  response,
  uploadFile
) => {
  addTrademarkParams.logoUrl = response.data;
};

// 数据(图片)上传之前的钩子
const beforeAvatarUpload: UploadProps["beforeUpload"] = (rawFile) => {
  if (
    rawFile.type == "image/jpeg" ||
    rawFile.type == "image/png" ||
    rawFile.type == "image/gif"
  ) {
    if (rawFile.size / 1024 / 1024 <= 5) {
      return true;
    }
  } else {
    return false;
  }
};

// 添加或修改品牌确定按钮的回调
const addTrademark = () => {
  formRef.value?.validate(async (isValid: boolean) => {
    if (isValid) {
      try {
        await reqAddOrUpdateTrademark(addTrademarkParams);

        dialogFormVisible.value = false;

        getTrademarkList();

        ElMessage({
          showClose: true,
          message: addTrademarkParams.id ? "修改品牌成功" : "添加品牌成功",
          type: "success",
        });
      } catch (error) {
        ElMessage({
          showClose: true,
          message: "添加品牌失败",
          type: "error",
        });
      }
    } else {
      ElMessage({
        showClose: true,
        message: "表单校验错误",
        type: "error",
      });
    }
  });
};

// 添加品牌按钮的回调
const addButtonHandler = () => {
  dialogFormVisible.value = true;
  addTrademarkParams.logoUrl = "";
  addTrademarkParams.tmName = "";
  addTrademarkParams.id = undefined;
  nextTick(() => {
    formRef.value?.resetFields();
  });
};

// 修改品牌按钮的回调
const updateTrademark = async (row: ITrademark) => {
  dialogFormVisible.value = true;

  nextTick(() => {
    formRef.value?.resetFields();
    addTrademarkParams.id = row.id;
    addTrademarkParams.logoUrl = row.logoUrl;
    addTrademarkParams.tmName = row.tmName;
  });
};

// 自定义表单tmName的校验规则
const validatePass = (rule: any, value: any, callback: any) => {
  if (value) {
    callback();
  } else {
    callback(new Error("表单校验不通过"));
  }
};

// 表单校验规则
const rules = reactive<FormRules>({
  tmName: [
    { required: true, message: "必须输入品牌名称", trigger: "blur" },
    {
      required: true,
      validator: validatePass,
      message: "品牌名称应在2到10位之间",
      trigger: "change",
    },
  ],
  logoUrl: [{ required: true, message: "请上传品牌LOGO" }],
});

// 删除品牌按钮的回调
const deleteTrademark = async (row: ITrademark) => {
  await reqDeleteTrademark(row.id);

  ElMessage({
    showClose: true,
    message: "删除成功",
    type: "success",
  });

  getTrademarkList(currentPage.value);
};

onMounted(() => {
  getTrademarkList();
});
</script>

<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.dialog-footer button:first-child {
  margin-right: 10px;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
